import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants/app_colors.dart';
import '../services/deepseek_service.dart';
import '../models/thought_record.dart';
import '../models/database_helper.dart';
import 'thought_reflection_screen.dart';

class NewThoughtScreen extends StatefulWidget {
  const NewThoughtScreen({Key? key}) : super(key: key);

  @override
  State<NewThoughtScreen> createState() => _NewThoughtScreenState();
}

class _NewThoughtScreenState extends State<NewThoughtScreen> {
  final _thoughtController = TextEditingController();
  bool _isLoading = false;

  @override
  void dispose() {
    _thoughtController.dispose();
    super.dispose();
  }

  Future<void> _analyzeThought() async {
    if (_thoughtController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入你的想法')),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final deepseekService = DeepseekService();
      final analysis = await deepseekService.analyzeThought(_thoughtController.text);

      // 保存想法记录到数据库
      final thoughtRecord = ThoughtRecord(
        thought: _thoughtController.text,
        distortionLabels: analysis.distortionLabels,
        emotionalIntensity: analysis.emotionalIntensity,
        timestamp: DateTime.now(),
      );
      
      final savedRecord = await DatabaseHelper.instance.insertThoughtRecord(thoughtRecord);

      if (!mounted) return;

      // 导航到反思页面
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => ThoughtReflectionScreen(
            thoughtRecord: savedRecord,
          ),
        ),
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('分析失败: ${e.toString()}')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(
          '想法重塑',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Text(
            //   '此刻的想法是什么？',
            //   style: GoogleFonts.zcoolKuaiLe(
            //     fontSize: 24,
            //     fontWeight: FontWeight.bold,
            //   ),
            // ),
            const SizedBox(height: 8),
            Text(
              '请描述你的消极想法',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 16,
                color: AppColors.textSecondary,
              ),
            ),
            const SizedBox(height: 24),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: TextField(
                controller: _thoughtController,
                maxLines: 5,
                decoration: InputDecoration(
                  hintText: '例如:我总是做不好事情',
                  hintStyle: GoogleFonts.zcoolKuaiLe(
                    color: AppColors.textSecondary,
                  ),
                  contentPadding: const EdgeInsets.all(16),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(16),
                    borderSide: BorderSide.none,
                  ),
                  filled: true,
                  fillColor: Colors.white,
                ),
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 16,
                  color: AppColors.textPrimary,
                ),
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: ElevatedButton(
            onPressed: _isLoading ? null : _analyzeThought,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              elevation: 0,
            ),
            child: _isLoading
                ? const SizedBox(
                    height: 24,
                    width: 24,
                    child: CircularProgressIndicator(
                      color: Colors.white,
                      strokeWidth: 2,
                    ),
                  )
                : Text(
                    '下一步',
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
          ),
        ),
      ),
    );
  }
} 